package com.example.xianji.activity;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.xianji.Contant;
import com.example.xianji.XJApplication;
import com.example.xianji.R;
import com.example.xianji.bean.YiJi_Class;
import com.example.xianji.constant.Constant;
import com.example.xianji.utils.sp.PreferenceEngine;
import com.example.xianji.widgets.CustomProgressDialog;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.BitmapDrawable;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.ClipboardManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

public class Main_QiYe_RuZhuActivity extends Activity implements OnClickListener {
    private ImageView qiye_ruzhu_back;
    private ClipboardManager clipboard;
    private InputMethodManager manager;
    private Button button_qiye_register, button_privonce, button_city, button_distrct;
    private CustomProgressDialog mCustomProgressDialog;
    //    private SharedPreferences sp;
//    private Editor ed;
    private EditText edittext_qiye_name, edittext_register_money, edittext_man_name, qiye_ruzhu_details;
    /** 固定号码 **/
    private EditText etFixPhone;
    /** 常用邮箱 **/
    private EditText etEmail;
    /** 拍照LinearLayout **/
    private LinearLayout llTakePhoto;
    /** 营业执照选择按钮 **/
    private Button btnTakePhoto;
    /** 营业执照显示FrameLayou**/
    private FrameLayout flBusinessLicense;
    /** 营业执照图片 **/
    private ImageView ivBusinessLicense;
    /** 关闭营业执照图片 **/
    private ImageView ivCloseLicense;
    /** 图片转换成的16进制数据 */
    private String photoStr = null;
    /** 手机号 **/
    private EditText etMobilePhone;
    /** 图形码LinearLayout **/
    private LinearLayout llAuthCode;
    /** 图形码 **/
    private EditText etAuthCode;
    /** 显示生成的图形码 **/
    private ImageView ivAuthCode;
    /** 验证码 LinearLayout **/
    private LinearLayout Linearlayout_yanzheng;
    /** 验证码 **/
    private EditText edittext_yanzhengma;
    private LinearLayout llPwd;
    /** 密码 **/
    private EditText etPwd;
    /** 返回的图形验证码 **/
    private Drawable d;
    /** 选择营业执照弹出框 **/
    private ListView lvTakePhoto;
    private PopupWindow popupWindow;
    private String[] groupTakePhoto = new String[]{"手机相册", "手机拍摄", "取消"};
    private LinearLayout linearlayout_phone_number;
    private PopupWindow show_popupWindow;
    private LinearLayout layout, linearlayout_qiye_ruzhu;
    private Button button_qiye_guimo, button_huoqu_yanzhengma;
    private ListView show_listview;
    private EditText button_choose_hangye;
    private ArrayList<YiJi_Class> list = new ArrayList<YiJi_Class>();
    private int province_id, city_id, distrct_id;
    private int province_indext = 1, city_indext = 1;
    private Boolean province_flag = false, city_flag = false, distrct_flag = false;
    private String group[] = new String[]{"大于100人", "51-100人", "21-50人", "5-20人", "5人"};
    private int Request_Permission_Take_Photo = 1;//拍照
    private int Request_Permission_Get_Photo = 2;//相册
    private TimeCount mTimeCount;
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    show_listview.setAdapter(new MyAdapter());
                    if (mCustomProgressDialog != null) {
                        mCustomProgressDialog.dismiss();
                        mCustomProgressDialog = null;
                    }
                    break;
                case 2:
                    ivAuthCode.setImageDrawable(d);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        setContentView(R.layout.activity_main__qi_ye__ru_zhu);
        //	XJApplication.getInstance().addActivity(this);
        qiye_ruzhu_back = (ImageView) findViewById(R.id.image_qiye_ruzhu_back);

        clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        hideKeyboard();
//        sp = getSharedPreferences("text", MODE_PRIVATE);
//        ed = sp.edit();
        button_qiye_register = (Button) findViewById(R.id.button_qiye_register);
        edittext_qiye_name = (EditText) findViewById(R.id.edittext_qiye_name);
        edittext_register_money = (EditText) findViewById(R.id.edittext_register_money);
        edittext_man_name = (EditText) findViewById(R.id.edittext_man_name);
        linearlayout_phone_number = (LinearLayout) findViewById(R.id.linearlayout_phone_number);
        Linearlayout_yanzheng = (LinearLayout) findViewById(R.id.Linearlayout_yanzheng);
        button_privonce = (Button) findViewById(R.id.button_privonce);
        button_city = (Button) findViewById(R.id.button_city);
        button_distrct = (Button) findViewById(R.id.button_distrct);
        etFixPhone = (EditText)findViewById(R.id.et_fix_phone_qiye_ruzhu);
        etEmail = (EditText)findViewById(R.id.et_email_qiye_ruzhu);
        llTakePhoto = (LinearLayout)findViewById(R.id.ll_take_photo_qiye_ruzhu);
        btnTakePhoto = (Button)findViewById(R.id.btn_take_photo_qiye_ruzhu);
        flBusinessLicense = (FrameLayout)findViewById(R.id.fl_business_license_qiye_ruzhu);
        ivBusinessLicense = (ImageView)findViewById(R.id.iv_business_license_qiye_ruzhu);
        ivCloseLicense = (ImageView)findViewById(R.id.iv_close_license_qiye_ruzhu);
        ivCloseLicense.setOnClickListener(this);
        btnTakePhoto.setOnClickListener(this);
        etMobilePhone = (EditText)findViewById(R.id.et_mobile_phone_qiye_ruzhu);
        etMobilePhone.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 11) {
                    new Thread() {
                        @Override
                        public void run() {
                            // 把网络访问的代码放在这里
                            LoadImageFromWebOperations(Contant.tuxing_yanzheng+ etMobilePhone.getText());
                        }
                    }.start();
                }
            }
        });
        llAuthCode = (LinearLayout)findViewById(R.id.ll_auth_code_qiye_ruzhu);
        etAuthCode = (EditText)findViewById(R.id.et_auth_code_qiye_ruzhu);
        ivAuthCode = (ImageView)findViewById(R.id.iv_auth_code_qiye_ruzhu);
        edittext_yanzhengma = (EditText) findViewById(R.id.edittext_yanzhengma);
        etPwd = (EditText)findViewById(R.id.et_pwd_qiye_ruzhu);

        linearlayout_qiye_ruzhu = (LinearLayout) findViewById(R.id.linearlayout_qiye_ruzhu);
        button_qiye_guimo = (Button) findViewById(R.id.button_qiye_ruzhu_guimo);
        button_choose_hangye = (EditText) findViewById(R.id.button_choose_hangye);
        qiye_ruzhu_details = (EditText) findViewById(R.id.qiye_ruzhu_details);
        button_huoqu_yanzhengma = (Button) findViewById(R.id.button_huoqu_yanzhengma);
        llPwd = (LinearLayout)findViewById(R.id.ll_pwd_qiye_ruzhu);

        mTimeCount = new TimeCount(60000, 1000);
//        if (PreferenceEngine.getInstance().getBoolean(Constant.SP.NAME, Constant.SP.KEY_XIANJI_DENGLU, false)) {
//            linearlayout_phone_number.setVisibility(View.GONE);
//            Linearlayout_yanzheng.setVisibility(View.GONE);
//        } else {
//            linearlayout_phone_number.setVisibility(View.VISIBLE);
//            Linearlayout_yanzheng.setVisibility(View.VISIBLE);
//        }
        qiye_ruzhu_back.setOnClickListener(this);
        button_qiye_register.setOnClickListener(this);
        button_privonce.setOnClickListener(this);
        button_city.setOnClickListener(this);
        button_distrct.setOnClickListener(this);
        linearlayout_qiye_ruzhu.setOnClickListener(this);
        button_qiye_guimo.setOnClickListener(this);
        button_huoqu_yanzhengma.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (PreferenceEngine.getInstance().getBoolean(Constant.SP.NAME, Constant.SP.KEY_XIANJI_DENGLU, false)) {
            linearlayout_phone_number.setVisibility(View.GONE);
            llAuthCode.setVisibility(View.GONE);
            Linearlayout_yanzheng.setVisibility(View.GONE);
            llPwd.setVisibility(View.GONE);
        }else{
            linearlayout_phone_number.setVisibility(View.VISIBLE);
            llAuthCode.setVisibility(View.VISIBLE);
            Linearlayout_yanzheng.setVisibility(View.VISIBLE);
            llPwd.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onClick(View arg0) {
        if (arg0.getId() == R.id.image_qiye_ruzhu_back) {
            Main_QiYe_RuZhuActivity.this.finish();
        } else if (arg0.getId() == R.id.button_qiye_register) {
            if (edittext_qiye_name.getText().toString().length() > 0) {
                if (edittext_man_name.getText().toString().length() > 0) {
                    if (button_choose_hangye.getText().toString().length() > 0) {
                        if (edittext_register_money.getText().toString().length() > 0) {
                            if (button_qiye_guimo.getText().toString().length() > 0) {
                                if (province_flag) {
                                    if(!TextUtils.isEmpty(photoStr)) {
                                        mCustomProgressDialog = CustomProgressDialog.createDialog(Main_QiYe_RuZhuActivity.this);
                                        mCustomProgressDialog.setCanceledOnTouchOutside(false);
                                        mCustomProgressDialog.show();
                                        get_qiye_register();
                                    }else{
                                        Toast.makeText(Main_QiYe_RuZhuActivity.this, "请选择营业执照", Toast.LENGTH_SHORT).show();
                                    }
                                } else {
                                    Toast.makeText(Main_QiYe_RuZhuActivity.this, "请选择省份", Toast.LENGTH_SHORT).show();
                                }
                            } else {
                                Toast.makeText(Main_QiYe_RuZhuActivity.this, "请选择企业规模", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(Main_QiYe_RuZhuActivity.this, "请输入注册资金", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(Main_QiYe_RuZhuActivity.this, "请输入从事行业", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(Main_QiYe_RuZhuActivity.this, "请输入联系人", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(Main_QiYe_RuZhuActivity.this, "请输入公司名称", Toast.LENGTH_SHORT).show();
            }
        } else if (arg0.getId() == R.id.button_privonce) {
            Photo_show();
            show_popupWindow.showAtLocation(findViewById(R.id.qiye_ruzhu), Gravity.BOTTOM, 0, 0);
            mCustomProgressDialog = CustomProgressDialog.createDialog(this);
            mCustomProgressDialog.setCanceledOnTouchOutside(false);
            mCustomProgressDialog.show();
            get_province();
            show_listview.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                                        int arg2, long arg3) {
                    province_id = list.get(arg2).getId();
                    button_privonce.setText(list.get(arg2).getName());
                    button_privonce.setTextColor(getResources().getColor(R.color.black3F));
                    province_indext++;
                    if (province_indext > 2) {
                        button_city.setText("城市");
                        button_city.setTextColor(getResources().getColor(R.color.gray98));
                        button_distrct.setText("区域");
                        button_distrct.setTextColor(getResources().getColor(R.color.gray98));
                        city_flag = false;
                        distrct_flag = false;
                    }
                    province_flag = true;
                    if (show_popupWindow != null) {
                        show_popupWindow.dismiss();
                        show_popupWindow = null;
                    }
                }
            });
        } else if (arg0.getId() == R.id.button_city) {
            if (province_flag) {
                Photo_show();
                show_popupWindow.showAtLocation(findViewById(R.id.qiye_ruzhu), Gravity.BOTTOM, 0, 0);
                mCustomProgressDialog = CustomProgressDialog.createDialog(this);
                mCustomProgressDialog.setCanceledOnTouchOutside(false);
                mCustomProgressDialog.show();
                if (button_privonce.getText().toString().equals("北京") || button_privonce.getText().toString().equals("上海") || button_privonce.getText().toString().equals("天津") ||
                        button_privonce.getText().toString().equals("香港") || button_privonce.getText().toString().equals("台湾")
                        ) {
                    get_teshu_province();
                } else {
                    get_city();
                }
                show_listview.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View arg1,
                                            int arg2, long arg3) {
                        city_id = list.get(arg2).getId();
                        button_city.setText(list.get(arg2).getName());
                        button_city.setTextColor(getResources().getColor(R.color.black3F));
                        city_indext++;
                        if (city_indext > 2) {
                            button_distrct.setText("区域");
                            button_distrct.setTextColor(getResources().getColor(R.color.gray98));
                            distrct_flag = false;
                        }
                        city_flag = true;
                        if (show_popupWindow != null) {
                            show_popupWindow.dismiss();
                            show_popupWindow = null;
                        }
                    }
                });
            } else {
                Toast.makeText(Main_QiYe_RuZhuActivity.this, "请先选择省份", Toast.LENGTH_SHORT).show();
            }

        } else if (arg0.getId() == R.id.button_distrct) {
            if (city_flag) {
                Photo_show();
                show_popupWindow.showAtLocation(findViewById(R.id.qiye_ruzhu), Gravity.BOTTOM, 0, 0);
                mCustomProgressDialog = CustomProgressDialog.createDialog(this);
                mCustomProgressDialog.setCanceledOnTouchOutside(false);
                mCustomProgressDialog.show();
                get_district();
                show_listview.setOnItemClickListener(new OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        distrct_id = list.get(position).getId();
                        button_distrct.setText(list.get(position).getName());
                        button_distrct.setTextColor(getResources().getColor(R.color.black3F));
                        distrct_flag = true;
                        if (show_popupWindow != null) {
                            show_popupWindow.dismiss();
                            show_popupWindow = null;
                        }
                    }
                });
            } else {
                Toast.makeText(Main_QiYe_RuZhuActivity.this, "请先选择城市", Toast.LENGTH_SHORT).show();
            }

        } else if (arg0.getId() == R.id.linearlayout_qiye_ruzhu) {
            if (show_popupWindow != null) {
                show_popupWindow.dismiss();
                show_popupWindow = null;
            }
        } else if (arg0.getId() == R.id.button_qiye_ruzhu_guimo) {
            Photo_show();
            show_popupWindow.showAtLocation(findViewById(R.id.qiye_ruzhu), Gravity.BOTTOM, 0, 0);
            show_listview.setAdapter(new ArrayAdapter<String>(Main_QiYe_RuZhuActivity.this, R.layout.information_show_photo_item, R.id.show_photo_item_text, group));
            show_listview.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                                        int arg2, long arg3) {
                    button_qiye_guimo.setText(group[arg2]);
                    button_qiye_guimo.setTextColor(getResources().getColor(R.color.black3F));
                    if (show_popupWindow != null) {
                        show_popupWindow.dismiss();
                        show_popupWindow = null;
                    }
                }
            });
        } else if (arg0.getId() == R.id.button_huoqu_yanzhengma) {  //获取短信验证码
            if (etMobilePhone.getText().toString().length() == 11) {
                if(etAuthCode.getText().toString().trim().length()>0) {
                    mTimeCount.start();
                    huoqu_yanzhengma();
                }else{
                    Toast.makeText(Main_QiYe_RuZhuActivity.this, "请输入图形码", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(Main_QiYe_RuZhuActivity.this, "请输入手机号", Toast.LENGTH_SHORT).show();
            }
        }else if(arg0.getId()==R.id.btn_take_photo_qiye_ruzhu){  //营业执照
            initListView();
            popupWindow.showAtLocation(findViewById(R.id.qiye_ruzhu), Gravity.BOTTOM, 0, 0);
            lvTakePhoto.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                                        int arg2, long arg3) {
                    if (groupTakePhoto[arg2].equals("手机相册")) {
                        popupWindow.dismiss();
                        if (permissionCheck(Constant.Permission.PERMISSION_XIANGCE)) {
                            Intent intent = new Intent(Intent.ACTION_PICK, null);

                            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                            startActivityForResult(intent, 1);
                        } else {
                            ActivityCompat.requestPermissions(Main_QiYe_RuZhuActivity.this, Constant.Permission.PERMISSION_XIANGCE, Request_Permission_Get_Photo);
                        }
                    }
                    if (groupTakePhoto[arg2].equals("手机拍摄")) {
                        popupWindow.dismiss();
                        if (permissionCheck(Constant.Permission.PERMISSION_PAIZHAO)) {
                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            startActivityForResult(intent, 2);
                        } else {
                            ActivityCompat.requestPermissions(Main_QiYe_RuZhuActivity.this, Constant.Permission.PERMISSION_PAIZHAO, Request_Permission_Take_Photo);
                        }
                    }
                    if (groupTakePhoto[arg2].equals("取消")) {
                        popupWindow.dismiss();
                    }
                }
            });
        }else if(arg0.getId()==R.id.iv_close_license_qiye_ruzhu){
            photoStr = null;
            changeTakePhotoVisibile(true);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            switch (requestCode) {
                case 1:
                    if (data != null) {
                        startPhotoZoom(data.getData());
                    }
                    break;
                case 2:
                    if (data != null) {
                        Bitmap bitmap1 = (Bitmap) data.getExtras().get("data");
                        show(bitmap1);
                    }
                    break;
                case 3:
                    if (data != null) {
                        setPicToView(data);
                    }
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == Request_Permission_Take_Photo) {
            //拍照
            if (grantResults.length > 0) {
                boolean take_photo_flag = false;
                for (int i = 0; i < permissions.length; i++) {
                    if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                        take_photo_flag = true;
                    }
                }
                if (take_photo_flag) {
                    //申请成功，可以拍照
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(intent, 2);
                } else {
                    Toast.makeText(this, "请先开通权限哦", Toast.LENGTH_SHORT).show();
                }
            }
        } else if (requestCode == Request_Permission_Get_Photo) {
            //相册
            if (grantResults.length > 0) {
                boolean take_photo_flag = false;
                for (int i = 0; i < permissions.length; i++) {
                    if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                        take_photo_flag = true;
                    }
                }
                if (take_photo_flag) {
                    //申请成功，可以获取相册图片
                    Intent intent = new Intent(Intent.ACTION_PICK, null);
                    intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(intent, 1);
                } else {
                    Toast.makeText(this, "请先开通权限哦", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    /**
     * 获取短信验证
     */
    public void huoqu_yanzhengma() {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams parms = new RequestParams();
        parms.addBodyParameter("code_from", "info");
        parms.addBodyParameter("picverify", etAuthCode.getText().toString().trim());
        parms.addBodyParameter("mobile", etMobilePhone.getText().toString());
        httpUtils.send(HttpMethod.POST, Contant.message_yanzheng, parms, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                try {
                    JSONObject obj = new JSONObject(arg0.result);
                    Toast.makeText(Main_QiYe_RuZhuActivity.this, obj.getString("msg"), Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 省份请求
     */
    public void get_province() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("pid", 0);
        JSONObject params = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest(Method.POST, Contant.place,
                params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getInt("status") == 1) {
                        list.clear();
                        JSONArray array = response.getJSONArray("data");
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject obj = array.getJSONObject(i);
                            YiJi_Class mYiJi_Class = new YiJi_Class();
                            mYiJi_Class.setId(obj.getInt("id"));
                            mYiJi_Class.setName(obj.getString("name"));
                            list.add(mYiJi_Class);
                        }
                        handler.sendEmptyMessage(1);
                    } else {
                        Toast.makeText(Main_QiYe_RuZhuActivity.this, response.getString("msg"), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                if (mCustomProgressDialog != null) {
                    mCustomProgressDialog.dismiss();
                    mCustomProgressDialog = null;
                }
                if (show_popupWindow != null) {
                    show_popupWindow.dismiss();
                    show_popupWindow = null;
                }
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    /**
     * 省份请求
     */
    public void get_teshu_province() {
        list.clear();
        YiJi_Class mYiJi_Class = new YiJi_Class();
        mYiJi_Class.setId(province_id);
        mYiJi_Class.setName(button_privonce.getText().toString());
        list.add(mYiJi_Class);
        handler.sendEmptyMessage(1);
    }

    /**
     * 城市请求
     */
    public void get_district() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        JSONObject params = new JSONObject(map);

        JsonObjectRequest request = new JsonObjectRequest(Method.POST, Contant.place,
                params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getInt("status") == 1) {
                        list.clear();
                        JSONArray array = response.getJSONArray("data");
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject obj = array.getJSONObject(i);
                            YiJi_Class mYiJi_Class = new YiJi_Class();
                            mYiJi_Class.setId(obj.getInt("id"));
                            mYiJi_Class.setName(obj.getString("name"));
                            list.add(mYiJi_Class);
                        }
                        handler.sendEmptyMessage(1);
                    } else {
                        Toast.makeText(Main_QiYe_RuZhuActivity.this, response.getString("msg"), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                if (mCustomProgressDialog != null) {
                    mCustomProgressDialog.dismiss();
                    mCustomProgressDialog = null;
                }
                if (show_popupWindow != null) {
                    show_popupWindow.dismiss();
                    show_popupWindow = null;
                }
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    /**
     * 地区请求
     */
    public void get_city() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("pid", province_id);
        JSONObject params = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest(Method.POST, Contant.place,
                params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getInt("status") == 1) {
                        list.clear();
                        JSONArray array = response.getJSONArray("data");
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject obj = array.getJSONObject(i);
                            YiJi_Class mYiJi_Class = new YiJi_Class();
                            mYiJi_Class.setId(obj.getInt("id"));
                            mYiJi_Class.setName(obj.getString("name"));
                            list.add(mYiJi_Class);
                        }
                        handler.sendEmptyMessage(1);
                    } else {
                        Toast.makeText(Main_QiYe_RuZhuActivity.this, response.getString("msg"), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                if (mCustomProgressDialog != null) {
                    mCustomProgressDialog.dismiss();
                    mCustomProgressDialog = null;
                }
                if (show_popupWindow != null) {
                    show_popupWindow.dismiss();
                    show_popupWindow = null;
                }
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    private void Photo_show() {
        layout = (LinearLayout) LayoutInflater.from(
                Main_QiYe_RuZhuActivity.this).inflate(
                R.layout.information_shoow_photo, null);
        show_listview = (ListView) layout.findViewById(R.id.information_photo_listview);

        show_listview.setCacheColorHint(0);
        if (show_popupWindow == null) {
            show_popupWindow = new PopupWindow(layout, WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.WRAP_CONTENT);
            show_popupWindow.setBackgroundDrawable(new BitmapDrawable());
            show_popupWindow.setHeight(700);
            show_popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
            show_popupWindow.update();
            show_popupWindow.setOutsideTouchable(false);
            show_popupWindow.setFocusable(false);
            show_popupWindow.setContentView(layout);
        }
    }

    /**
     * 隐藏软键盘
     */
    private void hideKeyboard() {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                manager.hideSoftInputFromWindow(getCurrentFocus()
                        .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    public void get_qiye_register() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        if (PreferenceEngine.getInstance().getBoolean(Constant.SP.NAME, Constant.SP.KEY_XIANJI_DENGLU, false)) {
            map.put("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
        } else {
            map.put("mobile", etMobilePhone.getText().toString());
            map.put("mverify", edittext_yanzhengma.getText().toString());
            map.put("password",etPwd.getText().toString().trim());
        }
        //集合转数组
        //  Integer[] values= Main_Choose_HangyeActivity.indext.toArray(new Integer[ Main_Choose_HangyeActivity.indext.size()]);
        map.put("category_id", button_choose_hangye.getText().toString());
        map.put("title", edittext_qiye_name.getText().toString());
        map.put("capital", edittext_register_money.getText().toString());
        map.put("username", edittext_man_name.getText().toString());
        map.put("province", province_id);
        map.put("city", city_id);
        map.put("district", distrct_id);
        map.put("scope", button_qiye_guimo.getText().toString());
        map.put("details", qiye_ruzhu_details.getText().toString());
        map.put("email",etEmail.getText().toString());
        map.put("tel",etFixPhone.getText().toString());
        map.put("licence",photoStr);
        map.put("code_from","register");

        JSONObject params = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest(Method.POST, Contant.qiye_ruzhu,
                params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    Toast.makeText(Main_QiYe_RuZhuActivity.this, response.getString("msg"), Toast.LENGTH_SHORT).show();
                    if (response.getInt("status") == 1) {

                        if (mCustomProgressDialog != null) {
                            mCustomProgressDialog.dismiss();
                            mCustomProgressDialog = null;
                        }
                        Contant.login_resume = 1;
                        Main_QiYe_RuZhuActivity.this.finish();
                    } else {
                        if (mCustomProgressDialog != null) {
                            mCustomProgressDialog.dismiss();
                            mCustomProgressDialog = null;
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                if (mCustomProgressDialog != null) {
                    mCustomProgressDialog.dismiss();
                    mCustomProgressDialog = null;
                }
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    /** 获取图形验证码 **/
    private void getAuthCode(){
        XJApplication.cachThreadPool.execute(new Runnable() {
            @Override
            public void run() {

            }
        });
    }

    class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int arg0) {
            return arg0;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Holder mHolder;
            if (convertView == null) {
                mHolder = new Holder();
                convertView = View.inflate(Main_QiYe_RuZhuActivity.this, R.layout.listview_item_layout, null);
                mHolder.place_text = (TextView) convertView.findViewById(R.id.place_text);
                convertView.setTag(mHolder);
            }
            mHolder = (Holder) convertView.getTag();
            mHolder.place_text.setText(list.get(position).getName());
            return convertView;
        }
    }

    class Holder {
        TextView place_text;
    }

    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            button_huoqu_yanzhengma.setText("重新获取");
            button_huoqu_yanzhengma.setBackgroundColor(getResources().getColor(R.color.blue22));
        }

        @Override
        public void onTick(long millisUntilFinished) {
            String str = new SimpleDateFormat("ss").format(Long.valueOf(millisUntilFinished));
            if (str.equals("00")) {
                button_huoqu_yanzhengma.setText("60秒");
            }
            button_huoqu_yanzhengma.setText(str + "秒");
            button_huoqu_yanzhengma.setBackgroundColor(getResources().getColor(R.color.gray98));
        }
    }

    /**
     * 通过URL加载ImageView
     *
     * @param url
     * @return
     */
    private Drawable LoadImageFromWebOperations(String url) {
        try {
            InputStream is = (InputStream) new URL(url).getContent();
            d = Drawable.createFromStream(is, "src name");
            handler.sendEmptyMessage(2);
            return d;
        } catch (Exception e) {
            System.out.println("Exc=" + e);
            return null;
        }
    }

    private void initListView() {
        layout = (LinearLayout) LayoutInflater.from(
                Main_QiYe_RuZhuActivity.this).inflate(
                R.layout.popwindow_touxiang, null);
        lvTakePhoto = (ListView) layout.findViewById(R.id.lv_take_photo_popwindow);
        lvTakePhoto.setCacheColorHint(0);
        lvTakePhoto.setAdapter(new ArrayAdapter<String>(Main_QiYe_RuZhuActivity.this,
                R.layout.text_touxiang, R.id.text, groupTakePhoto));
        popupWindow = new PopupWindow(layout, WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        popupWindow.setAnimationStyle(R.style.MyPopWindowAnimStyle);
        popupWindow.update();
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setContentView(layout);
    }

    private boolean permissionCheck(String[] permissionManifest) {
        if (Build.VERSION.SDK_INT >= 23) {
            boolean permissionState = true;
            for (String permission : permissionManifest) {
                if (ContextCompat.checkSelfPermission(this, permission)
                        != PackageManager.PERMISSION_GRANTED) {
                    permissionState = false;
                }
            }
            if (!permissionState) {
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

    public void show(Bitmap photo) {
        changeTakePhotoVisibile(false);
        ivBusinessLicense.setImageBitmap(photo);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        photo.compress(Bitmap.CompressFormat.PNG, 100, stream);// (0 - 100)压缩文件
        byte[] bt = stream.toByteArray();
        photoStr = byte2hex(bt);
    }

    /**
     * 二进制转字符串
     *
     * @param b
     * @return
     */
    public static String byte2hex(byte[] b) {
        StringBuffer sb = new StringBuffer();
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1) {
                sb.append("0" + stmp);
            } else {
                sb.append(stmp);
            }
        }
        return sb.toString();
    }

    /**
     * 将图片转换成十六进制字符串
     *
     * @param picdata
     */
    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            changeTakePhotoVisibile(false);
            ivBusinessLicense.setImageBitmap(photo);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            photo.compress(Bitmap.CompressFormat.PNG, 100, stream);// (0 - 100)压缩文件
            byte[] bt = stream.toByteArray();
            photoStr = byte2hex(bt);
        }
    }

    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "false");
        // aspectX,aspectY 是宽高的比例，这里设置正方形
//        intent.putExtra("aspectX", 1);
//        intent.putExtra("aspectY", 1);
        //设置要裁剪的宽高
//        intent.putExtra("outputX", 90);
//        intent.putExtra("outputY", 90);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
        String[] pojo = {MediaStore.Images.Media.DATA};

        Cursor cursor = managedQuery(uri, pojo, null,
                null,
                null);
    }

    private void changeTakePhotoVisibile(boolean isVisible){
        if(isVisible) {
            llTakePhoto.setVisibility(View.VISIBLE);
            flBusinessLicense.setVisibility(View.GONE);
        }else{
            llTakePhoto.setVisibility(View.GONE);
            flBusinessLicense.setVisibility(View.VISIBLE);
        }
    }
}
